package com.example.com.daervideo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.com.daervideo.activitys.loginRegist.LoginActivity;
import com.example.com.daervideo.activitys.loginRegist.RegistActivity;
import com.google.gson.Gson;

import java.io.IOException;
import java.nio.charset.Charset;

import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.SPUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.Utf8;

class ResponseInterceptor implements Interceptor {
    private final Context mContext;

    public ResponseInterceptor(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody body = response.body();
        BufferedSource source = body.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        if (body.contentLength() != 0) {
            String result = buffer.clone().readString(Charset.forName("UTF-8"));
            BaseResponse baseResponse;
                baseResponse = new Gson().fromJson(result, BaseResponse.class);
                if (baseResponse.getCode() == 10300) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    SPUtils.getInstance().put("isFirst", true);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                    mContext.startActivity(intent);
                }
        }
        return response;
    }
}
